package com.cskaoyan.demo.controller;

import com.cskaoyan.demo.bean.MarketAdmin;
import com.cskaoyan.demo.bean.MarketUser;
import com.cskaoyan.demo.bean.common.BaseRespVo;
import com.cskaoyan.demo.bean.data.UserInfoBean;
import com.cskaoyan.demo.bean.data.LoginUserData;
import com.cskaoyan.demo.util.AuthenticationUtil;
import com.cskaoyan.demo.exception.InfoExpiredException;
import com.cskaoyan.demo.exception.NoInfoException;
import com.cskaoyan.demo.service.*;
import com.cskaoyan.demo.util.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.*;

/**
 * @author stone
 * @date 2023/03/16 17:53
 */
@RestController
@RequestMapping("wx/auth")
public class AuthController {

    @Autowired
    AuthService authService;


    @SneakyThrows
    @RequestMapping("info")
    @ResponseBody
    public BaseRespVo info() {


        MarketAdmin admin = null;
        try {
            admin = (MarketAdmin) AuthenticationUtil.getPrincipal();
        } catch (NoInfoException e) {
            return BaseRespVo.unAuthc();
        } catch (InfoExpiredException e) {
            return BaseRespVo.expired();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        Set<String> permissions = new HashSet<>(Arrays.asList("*"));

        data.put("perms", permissions);
        return BaseRespVo.ok(data);
    }

    @SneakyThrows
    @RequestMapping("login")
    @ResponseBody
    public BaseRespVo login(@RequestBody Map<String, String> map){
        String username = map.get("username");
        String password = map.get("password");

        MarketUser user = authService.query(username, password);

        if (user == null) {
            return BaseRespVo.unAuthc();
        }

        String token = WdTokenHolder.genKey(user);

        UserInfoBean userInfoBean = new UserInfoBean(username, user.getAvatar());
        LoginUserData data = new LoginUserData(userInfoBean, token);
        return BaseRespVo.ok(data);
    }

    @SneakyThrows
    @RequestMapping("loginout")
    @ResponseBody
    public BaseRespVo logout(@RequestHeader("X-CskaoyanMarket-Admin-Token") String token) {
        WdTokenHolder.destoryToken(token);
        return BaseRespVo.ok();
    }

}
